const koa = require('koa')
const Router = require('koa-router')
const staticCache = require('koa-static-cache')
const bodyParser = require('koa-bodyparser')
const path = require('path')

let todoData = {
    _id: 3,
    todo: [
        { id: 1, mes: '学习node', done: true },
        { id: 2, mes: '学习koa', done: false },
        { id: 3, mes: '学习mysql', done: false },
    ]
}

const app = new koa()
app.use(staticCache(path.join(__dirname, '/static')))
app.use(bodyParser())

const router = new Router()

router.get('/todolist', async ctx => {
    ctx.body = todoData.todo
})

router.post('/add', async ctx => {
    let mes = ctx.request.body.mes || ''
    if (!!mes) {
        let newTodo = {
            id: ++todoData._id,
            mes,
            done: false
        }
        todoData.todo.push(newTodo)
        return ctx.body = {
            code: 0,
            data: newTodo
        }
    }
    return ctx.body = {
        code: 1,
        mes: '参数错误'
    }
})

router.post('/del', async ctx => {
    let id = ctx.request.body.id
    if (!!id) {
        let index = todoData.todo.findIndex(item => {
            return item.id === id
        })
        todoData.todo.splice(index, 1)
        ctx.body = {
            code: 0,
            data: todoData.todo
        }
    } else {
        ctx.body = {
            code: 1,
            mes: '参数错误'
        }
    }
})

router.post('/change', async ctx => {
    let id = ctx.request.body.id
    if (!!id) {
        let cur_todo = todoData.todo.find(item => {
            return item.id === id
        })
        cur_todo.done = !cur_todo.done
        ctx.body = {
            code: 0,
            data: todoData.todo
        }
    }else{
        ctx.body = {
            code: 1,
            mes: '参数错误'
        }
    }
})

app.use(router.routes())

app.listen(80, '127.0.0.1')